<template>
  <view class="uv-page" style="background-color: #fff;">
    <view class="uv-demo-block">
      <view class="uv-demo-block__content">
        <uv-steps :current="stepCurrent" dot>
          <uv-steps-item :title=item.title :desc="item.desc" :error="item.error"
                         v-for="(item,index) in steps " :key="index"></uv-steps-item>
        </uv-steps>
        <uv-form :model="form" ref="form1" labelWidth="auto">
          <uv-form-item prop="taskName" label="任务名:" borderBottom>
            <uv-text :text="title" type="info"></uv-text>
          </uv-form-item>
          <uv-form-item prop="userName" required label="执行人:" borderBottom
                        @click="showUserSelect"
                        v-if="form.status === 0 && (userId === form.inspectorId)">

            <uv-input v-model="form.userName" disabled disabledColor="#ffffff" placeholder="请选择执行人"
                      border="none"></uv-input>
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
          <uv-form-item prop="userName" label="执行人:" borderBottom v-else>
            <uv-text :text="form.userName" type="info"></uv-text>
          </uv-form-item>
          <uv-form-item label="执行截止日期:" borderBottom>
            <uv-text :text="form.deadline" type="info"></uv-text>
          </uv-form-item>
          <uv-form-item prop="inspectorName" label="检查人:" borderBottom>
            <uv-text :text="form.inspectorName" type="info"></uv-text>
          </uv-form-item>
          <uv-form-item label="检查截止日期:" borderBottom>
            <uv-text :text="form.inspectDeadline" type="info"></uv-text>
          </uv-form-item>

          <view>
            <uv-divider text=" 任务说明 " :dashed="true"></uv-divider>
            <uv-text align="center" prefixIcon="error-circle-fill" iconStyle="color:red;" size="16"
                     color="primary" text="注意规则"></uv-text>
            <view class="uv-content">
              <uv-parse :content="form.announcements"></uv-parse>
              <uv-album v-if="sampleGraph.length > 0" :urls="sampleGraph" maxCount="3" multipleSize="160rpx"
                        singleSize="160rpx" space="8rpx"></uv-album>
            </view>

            <uv-form-item label="备注:" borderBottom v-if="form.remark">
              <uv-text :text="form.remark" type="info"></uv-text>
            </uv-form-item>
          </view>
          <view>
            <uv-divider text=" 作业 " :dashed="true"></uv-divider>
            <uv-form-item prop="items" label="作业图:">
              <view style="display: flex;align-items: flex-start;">
                <uv-upload :fileList="fileList1"
                           name="1"
                           multiple
                           :maxCount="10"
                           @afterRead="afterRead"
                           :uploadText="userPictureText"
                           @delete="deletePic"
                           :disabled="userPictureDisabled"
                           width="80"
                           height="80"
                           sizeType="compressed"
                           :deletable="!userPictureDisabled"></uv-upload>
              </view>
            </uv-form-item>
            <uv-form-item prop="suggestion" label="建议:">
              <uv-textarea v-model="form.suggestion" count placeholder="请输入建议"
                           :disabled="form.status === 1"></uv-textarea>
            </uv-form-item>

            <uv-form-item required prop="rejectReason" label="驳回原因:" v-if="form.rejectReason">
              <uv-text :text="form.rejectReason" type="info"></uv-text>
            </uv-form-item>
          </view>
          <view v-if="form.status !== 0">
            <uv-divider text=" 检查 " :dashed="true"></uv-divider>
            <uv-form-item prop="items" label="检查图:">
              <view style="display: flex;align-items: flex-start;">
                <uv-upload :fileList="fileList2"
                           name="2"
                           multiple
                           :maxCount="10"
                           @afterRead="afterRead"
                           :uploadText="commentPictureText"
                           @delete="deletePic"
                           :disabled="commentPictureDisabled"
                           width="80"
                           height="80"
                           sizeType="compressed"
                           :deletable="!commentPictureDisabled"></uv-upload>
              </view>
            </uv-form-item>

            <uv-form-item prop="comment" label="检查事项:">
              <uv-textarea v-model="form.comment" count placeholder="请输入检查事项"></uv-textarea>
            </uv-form-item>

            <uv-form-item prop="score" label="评分:" v-if="form.status === 2">
              <view style="display: flex;align-items: flex-start;" >
                <uv-rate size="20" v-model="form.score" :allowHalf="true" touchable @change="changeRate"></uv-rate>
                <uv-text type="info" :text="form.score"></uv-text>
              </view>
            </uv-form-item>
			<uv-form-item prop="deductPoints" label="扣分原因:" v-if="form.status === 2">
			  <uv-textarea v-model="form.deductPoints" count placeholder="请输入扣分原因"></uv-textarea>
			</uv-form-item>
          </view>
        </uv-form>


        <view class="bottom">
          <view class="check-task">
            <uv-button type="error" text="驳回" customStyle="margin-top: 10px;width:60%" @click="openModal()"
                       v-if="form.status === 1 && (userId === form.inspectorId) ">
            </uv-button>

            <uv-button class="check-task-item" type="primary" text="检查" customStyle="margin-top: 10px;width:60%"
                       @click="checkTask()"
                       v-if="form.status === 1 && (userId === form.inspectorId) ">
            </uv-button>
          </view>

          <view class="check-task">
            <uv-button type="warning" text="暂存" customStyle="margin-top: 10px;width:60%" @click="saveDraft()"
                       v-if="form.status === 0 && (userId === form.userId) && !deadlineStatus">
            </uv-button>
            <uv-button type="primary" text="提交" customStyle="margin-top: 10px;width:60%" @click="openSubmitModal()"
                       v-if="form.status === 0 && (userId === form.userId) && !deadlineStatus">
            </uv-button>
          </view>

          <view class="check-task">
            <uv-button type="primary" text="评分" customStyle="margin-top: 10px;width:60%" @click="openScoreModal()"
                       v-if="form.status === 2 && (authority.includes('admin') || authority.includes('store_manager'))">
            </uv-button>
          </view>

          <!-- 选择执行人 -->
          <uv-picker ref="userSelectPicker"
                     :columns="userData"
                     @confirm="userSelect"
                     keyName="realName"></uv-picker>

          <!-- 选择截止日期 -->
          <uv-datetime-picker :minDate="minDate" ref="deadlinePicker" v-model="deadlineDate"
                              mode="datetime"
                              :formatter="formatter"
                              @confirm="deadlineConfirm"
                              @cancel="deadlineCancel"></uv-datetime-picker>

          <!--  驳回弹窗  -->
          <uv-modal ref="modal" title="驳回原因" :asyncClose="true" @confirm="rejectTask" :showCancelButton="true">
            <uv-form :model="form" ref="formReject" labelWidth="auto">
              <uv-form-item prop="deadline" label="截止日期:" borderBottom @click="deadlineOpen">
                <uv-input v-model="form.deadline" disabled disabledColor="#ffffff" placeholder="请选择截止日期"
                          border="none"></uv-input>
              </uv-form-item>
              <uv-form-item prop="remark" label="原因:">
                <uv-textarea v-model="form.rejectReason" count placeholder="请输入驳回原因"></uv-textarea>
              </uv-form-item>
            </uv-form>
          </uv-modal>

          <!--  提交确认弹窗  -->
          <uv-modal ref="submitModal" title="提交确认" content='您确定要提交任务吗？' @confirm="submitTask"
                    align="center"
                    :showCancelButton="true"></uv-modal>

          <!--  评分确认弹窗  -->
          <uv-modal ref="scoreModal" title="评分" :content="`当前评分：${score} ，您确定要提交吗？`"
                    @confirm="bindPickerChange" align="center" :showCancelButton="true">
          </uv-modal>


        </view>
      </view>
    </view>
  </view>
</template>

<script>
import debounce from '@climblee/uv-ui/libs/function/debounce';
import {formatHm, formatTime, isToday, showToast} from '@/utils/media';

import TaskAPI from '@/api/task'
import UploadAPI from "@/api/upload";
import CommonAPI from "@/api/common";

export default {
  data() {
    return {
      title: '',
      index: 0,
      text: '',
      id: '',
      userData: [], // 待选用户列表
      deadlineDate: new Date().getTime(),
      minDate: new Date().getTime(),
      sampleGraph: [], // 示例图
      form: {
        taskName: '', //任务标题
        areaId: '', //区域ID
        picture: '', //任务图示例
        announcements: '',
        userPicture: '',
        type: '',
        suggestion: '', // 建议
        rejectReason: '', // 驳回原因
        score: 0,
		deductPoints:''
      },

      fileList1: [], // 上传的作业图
      userPictureDisabled: false,
      userPictureText: '',

      fileList2: [], // 上传的评分图片
      commentPictureDisabled: false,
      commentPictureText: '',
      score: 0,
      edit: 0,
      authority: 'employee', // admin、employee、store_manager、dept_manager
      userId: '',
      deadlineStatus: false,
      stepCurrent: 0,
      steps: []
    };
  },
  onReady() {
    this.$refs.deadlinePicker.setFormatter(this.formatter)
  },
  onLoad(e) {
    this.id = e.id
    this.edit = e.edit ? e.edit : 0
    this.authority = uni.getStorageSync('authInfo')?.authority
    this.userId = uni.getStorageSync('authInfo')?.userId
    this.taskDetail()
  },
  methods: {
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`
      }
      if (type === 'month') {
        return `${value}月`
      }
      if (type === 'day') {
        return `${value}日`
      }
      if (type === 'hour') {
        return `${value}时`
      }
      if (type === 'minute') {
        return `${value}分`
      }
      return value
    },
    // 截止日期选择
    deadlineOpen() {
      this.deadlineDate = this.form.deadline
      this.$refs.deadlinePicker.open();
    },
    deadlineConfirm(e) {
      this.form.deadline = formatTime(e.value)
      this.deadlineDate = formatTime(e.value)
    },
    deadlineCancel() {
      this.deadlineDate = new Date().getTime()
      this.form.deadline = ''
    },
    // 执行人选择
    showUserSelect() {
      this.$refs.userSelectPicker.open();
    },
    userSelect(e) {
      // 正确获取选中项
      const element = e.value[0] // 单列选择器取第一个元素
      this.form.userId = element.id
      this.form.userName = element.realName
      TaskAPI.taskSetExecutor(this.form).then(res => {
        if (res.code !== 200) {
          showToast({
            title: res.msg
          })
          return
        }
        showToast({
          title: '设置成功'
        })
      })
    },

    // 任务详情
    async taskDetail() {
      await CommonAPI.userAttendance().then(res => {
        if (res.code !== 200) {
          return
        }
        this.userData = [[...res.data]]
      })

      await TaskAPI.taskRecordDetail({
        id: this.id
      }).then(res => {
        if (res.code !== 200) {
          showToast({
            title: res.msg
          })
          return
        }
        this.form = res.data
        let title = ''
        if (this.form.areaName) {
          title = this.form.areaName + '-'
        }
        if (this.form.taskName) {
          title += this.form.taskName
        }
        if (this.form.timeType === 0) {
          title += '【午餐】'
        } else if (this.form.timeType === 1) {
          title += '【晚餐】'
        }
        this.title = title

        // 任务是否到截止日期
        if (this.form.deadline) {
          let now = new Date().getTime()
          let deadline = new Date(this.form.deadline).getTime()
          if (now > deadline) {
            this.deadlineStatus = true
          }
        }

        this.score = this.form.score

        // 示例图
        this.sampleGraph = this.form.sampleGraph?.split(',')

        // 根据状态显示上传按钮
        let status = this.form.status

        // 如果点击了去评分 作业图不允许上传
        if (status === 1 && this.edit === '0') {
          this.userPictureDisabled = true
          this.userPictureText = '禁用'
          this.commentPictureDisabled = false
        }
        if (status === 2 || status === 3) {
          this.userPictureDisabled = true
          this.userPictureText = '禁用'
          this.commentPictureDisabled = true
          this.commentPictureText = '禁用'
        }
        // 作业图
        if (this.form.userPicture !== '') {
          this.fileList1 = this.form.userPicture?.split(',').map(i => {
            return {
              url: i
            }
          })
        }
        // 评论图
        if (this.form.commentPicture !== '') {
          this.fileList2 = this.form.commentPicture?.split(',').map(i => {
            return {
              url: i
            }
          })
        }

        // 初始化步骤条
        this.stepsInit()
      })
    },
    stepsInit() {
      const status = this.form.status;
      const steps = [{
        idx: 0,
        title: '提交',
        desc: '--:--',
        error: false
      }, {
        idx: 1,
        title: '检查',
        desc: '--:--',
        error: false
      }, {
        idx: 2,
        title: '完成',
        desc: '--:--',
        error: false
      }]
      if (status === 0) {
        steps[0].title = '待提交'
        steps[0].error = true
        this.stepCurrent = 0
      }
      if (status === 1) {
        steps[0].title = '已提交'
        steps[0].desc = formatHm(this.form.submitTime)
        steps[1].title = '待检查'
        this.stepCurrent = 0
      }
      if (status === 2) {
        steps[0].title = '已提交'
        steps[0].desc = formatHm(this.form.submitTime)
        steps[1].title = '已检查'
        steps[1].desc = formatHm(this.form.commentTime)
        steps[2].title = '已完成'
        steps[2].desc = formatHm(this.form.commentTime)
        this.stepCurrent = 2
      }
      if (status === 3) {
        steps[0].title = '未提交'
        steps[0].error = true

        steps[1].title = '未检查'
        steps[1].error = true

        steps[2].title = '未完成'
        steps[2].error = true

        this.stepCurrent = 0
      }
      if (status === 4) {
        steps[0].desc = formatHm(this.form.submitTime)
        steps[0].title = '已提交'

        steps[1].title = '未检查'
        steps[1].error = true

        steps[2].title = '未完成'
        steps[2].error = true
        this.stepCurrent = 1
      }
      this.steps = steps
    },
    // 显示图片
    preview(list, index) {
      uni.previewImage({
        urls: list,
        count: index
      })
    },

    changeRate(e) {
      console.info(e)
      console.log('完整事件对象：', e)

      this.score = this.form.score

    },
    openScoreModal() {
      this.$refs.scoreModal.open()
    },
    // 修改评分
    bindPickerChange() {
      if (this.authority.includes('admin') || this.authority.includes('store_manager')) {
        // 是否当天的任务 非当天任务不允许评分
        if (!isToday(this.form.inspectDeadline)) {
          showToast({
            title: '非当天任务不允许评分'
          })
          return
        }

        TaskAPI.taskScore({
          id: this.id,
          score: this.form.score,
		  deductPoints: this.form.deductPoints
        }).then(res => {
          if (res.code === 200) {
            showToast({
              title: '评分已更新'
            })
          }
        })
      }
    },

    // 驳回
    openModal() {
      this.$refs.modal.open();
    },
    rejectTask() {
      if (!this.form.rejectReason) {
        showToast({
          title: '请输入驳回原因'
        })
        this.$refs.modal.closeLoading()
        return
      }
      // 校验截止日期
      let now = new Date().getTime()
      let deadline = new Date(this.form.deadline).getTime()
      if (now > deadline) {
        showToast({
          title: '截止日期小于当前时间'
        })
        this.$refs.modal.closeLoading()
        return
      }

      TaskAPI.taskReject({
        id: this.id,
        rejectReason: this.form.rejectReason,
        deadline: this.form.deadline
      }).then(res => {
        if (res.code !== 200) {
          showToast({
            title: res.msg
          })
          return
        }
        this.$refs.modal.close();

        uni.reLaunch({
          url: `/pages/usertask/usertask`
        })
      })
    },

    checkTask() {
      debounce(() => {

        if (this.fileList2.length > 0) {
          this.form.commentPicture = this.fileList2.map(i => i.url).join(',')
        }

        this.form.status = 2

        TaskAPI.taskCheck(this.form).then(res => {
          if (res.code !== 200) {
            showToast({
              title: res.code
            })
            return
          }
          showToast({
            title: res.code
          })

          uni.reLaunch({
            url: `/pages/usertask/usertask`
          })
        })
      })
    },

    // 暂存
    saveDraft() {
      debounce(() => {
        if (this.fileList1.length == 0) {
          showToast({
            title: '请上传图片'
          })
          return
        }
        this.form.userPicture = this.fileList1.map(i => i.url).join(',')
        // 这里需要调用修改接口 调用update接口
        TaskAPI.taskSaveDraft(this.form).then(res => {
          if (res.code !== 200) {
            showToast({
              title: res.msg
            })
            this.form.status = 0
            return
          }
          showToast({
            title: res.msg
          })
          uni.reLaunch({
            url: `/pages/usertask/usertask`
          })
        })
      })
    },

    openSubmitModal() {
      this.$refs.submitModal.open();
    },
    // 作业
    submitTask() {
      debounce(() => {
        if (this.fileList1.length == 0) {
          showToast({
            title: '请上传图片'
          })
          return
        }
        this.form.userPicture = this.fileList1.map(i => i.url).join(',')
        // 修改状态为 已提交
        this.form.status = 1
        // 这里需要调用修改接口 调用update接口
        TaskAPI.taskSubmit(this.form).then(res => {
          if (res.code !== 200) {
            showToast({
              title: res.msg
            })
            this.form.status = 0
            return
          }
          showToast({
            title: res.msg
          })

          uni.reLaunch({
            url: `/pages/usertask/usertask`
          })
        })
      })
    },

    // 删除图片
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1)
    },
    // 新增图片
    async afterRead(event) {
      console.info(event)
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file)
      let fileListLen = this[`fileList${event.name}`].length
      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: 'uploading',
          message: '上传中'
        })
      })
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url)
        let item = this[`fileList${event.name}`][fileListLen]
        this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
          status: 'success',
          message: '',
          url: result
        }))
        fileListLen++
      }
    },
    async uploadFilePromise(url) {
      let data = await UploadAPI.uploadFile(url)
      return data.link
    }
  }
}
</script>

<style lang="scss" scoped>
.uv-page {
  padding: 15px 15px 40px 15px;
}

.uv-demo-block {
  margin-bottom: 22px;
}

.uv-demo-block__title {
  font-size: 14px;
  color: #8f9ca2;
  margin-bottom: 8px;
}

.uv-demo-block__title {
  font-size: 14px;
  color: #8f9ca2;
  margin-bottom: 8px;
}

.uv-demo-block__content {
  flex-direction: row;
  flex-wrap: wrap;
  align-items: center;
}

.uv-content {
  padding: 24rpx;
}

.check-task {
  display: flex;
  justify-content: space-between;
  margin: 0 20rpx;
}
</style>
